﻿using System;
using System.Threading;
using System.Web;

namespace Softio.Mscd
{
    internal class HttpAsyncResult : IAsyncResult
    {
        private AsyncCallback _callback;
        private object _result;

        internal HttpAsyncResult(AsyncCallback cb, object state)
        {
            this._callback = cb;
            this.AsyncState = state;
            this.Status = RequestNotificationStatus.Continue;
        }

        internal HttpAsyncResult(AsyncCallback cb, object state, bool completed, object result, Exception error)
        {
            this._callback = cb;
            this._result = result;

            this.AsyncState = state;
            this.IsCompleted = completed;
            this.CompletedSynchronously = completed;
            this.Error = error;
            this.Status = RequestNotificationStatus.Continue;
            if (this.IsCompleted && (this._callback != null))
            {
                this._callback(this);
            }
        }

        internal void Complete(bool synchronous, object result, Exception error)
        {
            this.Complete(synchronous, result, error, RequestNotificationStatus.Continue);
        }

        internal void Complete(bool synchronous, object result, Exception error, RequestNotificationStatus status)
        {
            this._result = result;
            this.IsCompleted = true;
            this.CompletedSynchronously = synchronous;
            this.Error = error;
            this.Status = status;
            if (this._callback != null)
            {
                this._callback(this);
            }
        }

        internal object End()
        {
            if (this.Error != null)
            {
                throw new HttpException(null, this.Error);
            }
            return this._result;
        }

        internal void SetComplete()
        {
            this.IsCompleted = true;
        }

        public object AsyncState{get;private set;}
        public WaitHandle AsyncWaitHandle { get { return null; } }
        public bool CompletedSynchronously { get; private set; }
        public bool IsCompleted { get; private set; }
        internal Exception Error { get; private set; }
        internal RequestNotificationStatus Status { get; private set; }
    }
}